import { defineStore } from 'pinia'
import axios from '@/utils/axios'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    token: localStorage.getItem('token') || null,
    isAuthenticated: false
  }),
  
  actions: {
    async login(credentials) {
      try {
        const response = await axios.post('/api/auth/signin', credentials)
        const { token, id, username, email } = response.data
        
        this.token = token
        this.user = { id, username, email }
        this.isAuthenticated = true
        
        localStorage.setItem('token', token)
        axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
        
        return { success: true }
      } catch (error) {
        console.error('Login error:', error)
        return { 
          success: false, 
          message: error.response?.data?.message || '登录失败' 
        }
      }
    },
    
    async register(userData) {
      try {
        console.log('Registering user:', userData)
        const response = await axios.post('/api/auth/signup', userData)
        console.log('Registration response:', response.data)
        return { success: true, message: response.data.message }
      } catch (error) {
        console.error('Registration error:', error)
        return { 
          success: false, 
          message: error.response?.data?.message || '注册失败' 
        }
      }
    },
    
    logout() {
      this.user = null
      this.token = null
      this.isAuthenticated = false
      
      localStorage.removeItem('token')
      delete axios.defaults.headers.common['Authorization']
    },
    
    initializeAuth() {
      const token = localStorage.getItem('token')
      if (token) {
        this.token = token
        this.isAuthenticated = true
        axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
      }
    }
  }
})